package edu.pdx.cs.cs542s07.minichess;


/**
 * Stores physical information about a chess piece (type and color). 
 */
class Piece {
	
	static int next_id = 0;
	
	PieceType type;
	Color color;
	private int id;
	Piece(PieceType type, Color color) {
		this.type = type;
		this.color = color;
		this.id = next_id;
		next_id += 1;
	}
	
	/**
	 * Converts a character representing a space on the board into a Piece object representing
	 * the contents of that space. 
	 * @throws IllegalArgumentException if the character is not valid.
	 * @param c A character representing a piece, or an empty space on the board.
	 * @return a Piece (type and color) corresponding to the character. A period '.' will return null.
	 */
	static Piece charToPiece(char c) 
		throws BadCharacterException {
		
		Piece piece;
		
		// I decided to keep this a switch statement for simplicity. However, I've arranged the 
		// cases in a hand-waving approximation of descending order of likelihood of occurrance,
		// with white getting a slight prejudice. 
		switch(c) {
		case '.':
			piece = null;	break;
		case 'P':
			piece = new Piece(PieceType.PAWN, Color.WHITE);		break;
		case 'p':
			piece = new Piece(PieceType.PAWN, Color.BLACK);		break;
		case 'K':
			piece = new Piece(PieceType.KING, Color.WHITE);		break;
		case 'k':
			piece = new Piece(PieceType.KING, Color.BLACK);		break;
		case 'Q':
			piece = new Piece(PieceType.QUEEN, Color.WHITE); 	break;
		case 'q':
			piece = new Piece(PieceType.QUEEN, Color.BLACK);	break;
		case 'B':
			piece = new Piece(PieceType.BISHOP, Color.WHITE); 	break;
		case 'b':
			piece = new Piece(PieceType.BISHOP, Color.BLACK);	break;
		case 'N':
			piece = new Piece(PieceType.KNIGHT, Color.WHITE);	break;
		case 'n':
			piece = new Piece(PieceType.KNIGHT, Color.BLACK);	break;
		case 'R':
			piece = new Piece(PieceType.ROOK, Color.WHITE);		break;
		case 'r':
			piece = new Piece(PieceType.ROOK, Color.BLACK);		break;
	
		default:
			throw new BadCharacterException();
		}
		return piece;
	}
	/**
	 * Returns the character representing the given piece.
	 * @param p	The piece to represent
	 * @return the character representing that piece.
	 */
	char toChar() {
		
		char c;
		if (this.type == PieceType.PAWN) {
			c = 'p';
		} else if (this.type == PieceType.KING) {
			c = 'k';
		} else if (this.type == PieceType.QUEEN) {
			c = 'q';
		} else if (this.type == PieceType.BISHOP) {
			c = 'b';
		} else if (this.type == PieceType.KNIGHT) {
			c = 'n';
		} else /* must be a rook */ {
			c = 'r';
		}
		
		if (this.color == Color.WHITE) {
			c = Character.toUpperCase(c);
		}
		
		return c;  
	}
}